import {createSlice} from '@reduxjs/toolkit';
import {loginUrl} from "@/api/pages/login.ts";
import {getTokenUtil, removeTokenUtil, setTokenUtil} from "@/utils/tokenUtil.ts";

export const userSlice = createSlice({
    name: 'user',
    initialState: {
        userInfo: {},
        token: getTokenUtil(),
        routerList: [],
        menuList: [],
        roles: [],
        permissions: [],
        routerDataList: [],
        breadcrumbItems: [],
        isCollapse: window.innerWidth < 1192,
    },
    reducers: {
        // 设置状态
        setIsCollapse(state, action) {
            state.isCollapse = action.payload;
        },
        setUserInfo(state, action) {
            const result = action.payload
            state.userInfo = result;
        },
        setToken(state, action) {
            state.token = action.payload;
            setTokenUtil(action.payload);
        },
        removeToken(state) {
            removeTokenUtil();
            state.token = getTokenUtil();
        },
    },
});

// 为每个 case reducer 函数生成 Action creators
export const {setIsCollapse, setToken, setUserInfo, removeToken} = userSlice.actions;

export default userSlice.reducer;


/**
 * 用户进行登录
 * @param params 登录所需要的参数
 * @constructor
 */
export const AsyncUserLogin: any = (params: any) => {
    return (dispatch: any) => {
        return new Promise((resolve, reject) => {
            // 模拟异步请求
            try {
                loginUrl(params).then((res: any) => {
                    // 登录成功保存 token
                    dispatch(setToken(res.token));
                    resolve(res);
                }).catch((e) => {
                    reject(e);
                })
            } catch (e) {
                reject(e);
            }
        });
    };
};

/**
 * 退出登录
 */
export const AsyncUserLogout: any = () => {
    return (dispatch: any) => {
        return new Promise((resolve, reject) => {
            // 模拟异步请求
            try {
                dispatch(setToken(null));
                removeTokenUtil()
                dispatch(setUserInfo({}));
                resolve("退出成功");
            } catch (e) {
                reject(e);
            }
        });
    };

};


